package app.map;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;

import com.amap.api.services.core.AMapException;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.Inputtips.InputtipsListener;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;

import java.util.ArrayList;
import java.util.List;

import mainUI.AppActivity;
import menhoo.com.i8officelibrary.R;
import tools.ToastUtil;


/**
 * 输入提示功能实现
 */
public class InputtipsActivity extends AppActivity implements TextWatcher, InputtipsListener {

	private String city = "北京";
	private AutoCompleteTextView mKeywordText;
	private ListView minputlist;
	private AddresAdapter adapter;
	private List<Tip> tips;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_inputtip);
		city = getIntent().getStringExtra("city");
		String title = getIntent().getStringExtra("title");

		minputlist = (ListView)findViewById(R.id.inputlist);
		tips = new ArrayList<Tip>();
		adapter = new AddresAdapter(InputtipsActivity.this, tips);

		minputlist.setAdapter(adapter);
		mKeywordText = (AutoCompleteTextView)findViewById(R.id.input_edittext);
		mKeywordText.addTextChangedListener(this);

		minputlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Intent it = new Intent();
				it.putExtra("LaddressName", tips.get(position).getAddress());
				it.putExtra("SaddressName", tips.get(position).getDistrict());
				setResult(Activity.RESULT_OK, it);
				finish();
			}
		});
		setTitle(title);
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		String newText = s.toString().trim();
		InputtipsQuery inputquery = new InputtipsQuery(newText, city);
		inputquery.setCityLimit(true);
		Inputtips inputTips = new Inputtips(InputtipsActivity.this, inputquery);
		inputTips.setInputtipsListener(this);
		inputTips.requestInputtipsAsyn();
	}

	@Override
	public void afterTextChanged(Editable s) {}

	/**
	 * 输入提示结果的回调
	 * @param tipList
	 * @param rCode
	 */
	@Override
	public void onGetInputtips(final List<Tip> tipList, int rCode) {
		if (rCode == AMapException.CODE_AMAP_SUCCESS) {
			tips.clear();
			tips.addAll(tipList);
			adapter.notifyDataSetChanged();
		} else {
			ToastUtil.showerror(this.getApplicationContext(), rCode);
		}

	}



}
